package com.jxb.three;

import com.jxb.first.ListNode;

/**
 * 类注释
 *
 * @author jiaobo
 * @date Created in 2024/12/29 21:21
 **/
public class ReverseNodesInKGroup_25 {

    public static void main(String[] args) {

    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode begin;
        if (head == null || head.next == null || k==1 ) {
            return head;
        }
        ListNode dummmy = new ListNode(-1);
        dummmy.next = head;
        begin = dummmy;
        int i = 0;
        while (head != null) {
            i++;
            if (i%k == 0) {
                begin = reverse(begin,head.next);
                head = begin.next;
            }else {
                head = head.next;
            }
        }
        return dummmy.next;
    }

    private ListNode reverse(ListNode preSubList, ListNode subListNext) {
        ListNode startNode = preSubList.next;
        ListNode nextNode = startNode.next;
        ListNode inPreNode = preSubList;
        while (startNode.next != subListNext) {
            startNode.next = nextNode.next;
            nextNode.next = inPreNode.next;
            inPreNode.next = startNode.next;
        }
        return startNode;
    }

}
